package com.hakgc.demo.servlet;

import com.alibaba.fastjson.JSON;
import com.hakgc.rent.entity.User;
import com.hakgc.rent.service.UserService;
import com.hakgc.rent.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/11/19
 */
@WebServlet(name = "AjaxUsersServlet",urlPatterns = "/ajax/users")
public class AjaxUsersServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");


        // 获取所有用户集合
        UserService userService = new UserServiceImpl();
        List<User> userList = userService.findAll(name);

        // 将集合转换成JSON格式
        String json = JSON.toJSONString(userList);

        // JSON字符串响应给客户端
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println(json);
    }
}
